﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Justin.Service
{
    /// <summary>
    /// 全局唯一服务
    /// 启动进行服务的调用
    /// </summary>
    public static class ServieSingleton
    {
        /// <summary>
        /// 默认实现
        /// </summary>
        private static IServiceProvider defaultProvider = new ServiceSingletonProviderImpl();

        /// <summary>
        /// 调用引用
        /// 可以修改提供方
        /// </summary>
        private static volatile IServiceProvider instance = defaultProvider;

        /// <summary>
        /// 修改服务提供方
        /// </summary>
        /// <param name="provider"></param>
        public static void SetServiceProvider(IServiceProvider provider) {
            lock (instance) {
                instance = provider;
            }
        }

        /// <summary>
        /// 通过接口获取全局唯一服务
        /// </summary>
        /// <typeparam name="T">服务接口</typeparam>
        /// <returns>返回全局唯一服务实例</returns>
        public static T GetService<T>() where T : class {
            var obj = instance.GetService(typeof(T));
            var result = obj as T;
            if (result == null) {
                throw new ServiceNotFoundException(typeof(T));
            }
            return result;
        }
    }
}
